from myelin.Ns import MYELINS
from myelin.server.core.ft import ModelDriver

class AgentProfiler(object):
    __slots__ = ('root','locale',)
    
    newAgentDriver = staticmethod(ModelDriver.FromRepo)
    newProfilesDriver = staticmethod(ModelDriver.FromRepo)
    
    def __init__(self, root, locale=None):
        self.root = root
        self.locale = locale
    
    def createProfile(self, context, obj, model):
        #print "Node %s: %s, %s" % (model.rdf_value, root, locale)
        graphs = context.server.graphs
        value = graphs['agents']['public']
        if value:
            agentModel = model.rdf_clone(
                model.Initialize(
                    self.newAgentDriver(
                        context.repo,
                        value
                    )
                )
            )
        else:
            agentModel = model
            
        map = context.uriMapper.apply
        
        obj['nodeId'] = model.rdf_value
        
        m_join = agentModel.rdf_join
        value = m_join('foafNick')
        if value:
            obj['nick'] = value
        value = m_join('foafName')
        if value:
            obj['name'] = value
               
        locale = self.locale
        root = self.root
        def _profile(m):
            for p in m:
                #print "profile: %s" % p.rdf_value
                href = map(p.rdf_getDomain())
                if href.startswith('http://'):
                    if locale in p.dcLanguage:
                        return (p.rdf_value, href)
                    r = _profile(p.mTranslation)
                    if r: return r
                    # should we just return what we found?
                    # return p 
        
        value = graphs['profiles']['published']
        if value:
            model = model.rdf_clone(
                model.Initialize(
                    self.newProfilesDriver(
                        context.repo,
                        value
                    )
                )
            )
        
        value = _profile(model.mProfile)
        if value:
            obj['profile'] = {
                'nodeId' : value[0],
                'uri' : value[1],
            }
        else:
            object['profile'] = None
            
        return obj